package com.ruoyi.merchant.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.mapper.MerchantMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.merchant.domain.CouponManagement2;
import com.ruoyi.merchant.domain.dto.CouponCreateDTO;
import com.ruoyi.merchant.domain.dto.CouponQueryDTO;
import com.ruoyi.merchant.domain.dto.CouponUpdateDTO;
import com.ruoyi.merchant.domain.vo.CouponStatisticsVO;
import com.ruoyi.merchant.domain.vo.CouponVO;
import com.ruoyi.merchant.mapper.CouponManagementMapper2;
import com.ruoyi.merchant.service.ICouponManagementService2;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;

/**
 * 优惠券管理Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class CouponManagementService2Impl implements ICouponManagementService2 {
    
    @Autowired
    private CouponManagementMapper2 couponManagementMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询优惠券列表
     */
    @Override
    public List<CouponVO> selectCouponList(CouponQueryDTO queryDTO) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        List<CouponManagement2> list = couponManagementMapper.selectCouponList(String.valueOf(merchantId), queryDTO);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    /**
     * 查询优惠券详情
     */
    @Override
    public CouponVO selectCouponById(String couponId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        CouponManagement2 coupon = couponManagementMapper.selectCouponById(couponId, String.valueOf(merchantId));
        if (coupon == null) {
            throw new ServiceException("优惠券不存在或无权访问");
        }
        return convertToVO(coupon);
    }

    /**
     * 新增优惠券
     */
    @Override
    @Transactional
    public int insertCoupon(CouponCreateDTO createDTO) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        Merchant merchant = merchantMapper.selectMerchantById(merchantId);

        // 验证优惠券参数
        validateCouponParams(createDTO);
        
        // 生成优惠券编码
        String couponCode = generateCouponCode();
        
        // 检查优惠券编码唯一性
        if (couponManagementMapper.checkCouponCodeUnique(couponCode, null) > 0) {
            throw new ServiceException("优惠券编码已存在，请重试");
        }
        
        CouponManagement2 coupon = new CouponManagement2();
        BeanUtils.copyProperties(createDTO, coupon);
        
        // 设置基本信息
        coupon.setCouponId(UUID.randomUUID().toString().replace("-", ""));
        coupon.setCouponCode(couponCode);
        coupon.setMerchantId(String.valueOf(merchantId));
        coupon.setMerchantName(merchant.getMerchantName());
        
        // 初始化数量
        coupon.setUsedQuantity(0);
        coupon.setRemainingQuantity(createDTO.getTotalQuantity());
        
        // 初始状态：待审核
        coupon.setStatus(0);
        coupon.setApprovalStatus(0);
        
        // 设置创建人
        try {
            coupon.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            coupon.setCreateBy("merchant");
        }
        
        return couponManagementMapper.insertCoupon(coupon);
    }

    /**
     * 修改优惠券
     */
    @Override
    @Transactional
    public int updateCoupon(CouponUpdateDTO updateDTO) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询原优惠券信息
        CouponManagement2 existCoupon = couponManagementMapper.selectCouponById(
            updateDTO.getCouponId(), String.valueOf(merchantId));
        if (existCoupon == null) {
            throw new ServiceException("优惠券不存在或无权访问");
        }
        
        // 只有待审核、审核拒绝的优惠券可以编辑
        if (existCoupon.getApprovalStatus() != 0 && existCoupon.getApprovalStatus() != 2) {
            throw new ServiceException("只有待审核或审核拒绝的优惠券可以编辑");
        }
        
        // 验证优惠券参数
        validateCouponParams(updateDTO);
        
        CouponManagement2 coupon = new CouponManagement2();
        BeanUtils.copyProperties(updateDTO, coupon);
        coupon.setMerchantId(String.valueOf(merchantId));
        
        // 更新剩余数量
        Integer usedQuantity = existCoupon.getUsedQuantity();
        coupon.setRemainingQuantity(updateDTO.getTotalQuantity() - usedQuantity);
        
        // 重新提交审核
        coupon.setStatus(0);
        coupon.setApprovalStatus(0);
        
        // 设置更新人
        try {
            coupon.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            coupon.setUpdateBy("merchant");
        }
        
        return couponManagementMapper.updateCoupon(coupon);
    }

    /**
     * 删除优惠券
     */
    @Override
    @Transactional
    public int deleteCoupon(String couponId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询优惠券信息
        CouponManagement2 coupon = couponManagementMapper.selectCouponById(couponId, String.valueOf(merchantId));
        if (coupon == null) {
            throw new ServiceException("优惠券不存在或无权访问");
        }
        
        // 已发布的优惠券不能删除
        if (coupon.getStatus() == 3) {
            throw new ServiceException("已发布的优惠券不能删除");
        }
        
        return couponManagementMapper.deleteCoupon(couponId, String.valueOf(merchantId));
    }

    /**
     * 发布优惠券
     */
    @Override
    @Transactional
    public int publishCoupon(String couponId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询优惠券信息
        CouponManagement2 coupon = couponManagementMapper.selectCouponById(couponId, String.valueOf(merchantId));
        if (coupon == null) {
            throw new ServiceException("优惠券不存在或无权访问");
        }
        
        // 只有审核通过的优惠券可以发布
        if (coupon.getApprovalStatus() != 1) {
            throw new ServiceException("只有审核通过的优惠券可以发布");
        }
        
        // 检查有效期
        Date now = new Date();
        if (coupon.getValidEndTime().before(now)) {
            throw new ServiceException("优惠券已过期，无法发布");
        }
        
        // 更新状态为已发布
        return couponManagementMapper.updateCouponStatus(couponId, String.valueOf(merchantId), 3);
    }

    /**
     * 暂停优惠券
     */
    @Override
    @Transactional
    public int pauseCoupon(String couponId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询优惠券信息
        CouponManagement2 coupon = couponManagementMapper.selectCouponById(couponId, String.valueOf(merchantId));
        if (coupon == null) {
            throw new ServiceException("优惠券不存在或无权访问");
        }
        
        // 只有已发布的优惠券可以暂停
        if (coupon.getStatus() != 3) {
            throw new ServiceException("只有已发布的优惠券可以暂停");
        }
        
        // 更新状态为已暂停
        return couponManagementMapper.updateCouponStatus(couponId, String.valueOf(merchantId), 4);
    }

    /**
     * 恢复优惠券
     */
    @Override
    @Transactional
    public int resumeCoupon(String couponId) {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 查询优惠券信息
        CouponManagement2 coupon = couponManagementMapper.selectCouponById(couponId, String.valueOf(merchantId));
        if (coupon == null) {
            throw new ServiceException("优惠券不存在或无权访问");
        }
        
        // 只有已暂停的优惠券可以恢复
        if (coupon.getStatus() != 4) {
            throw new ServiceException("只有已暂停的优惠券可以恢复");
        }
        
        // 检查有效期
        Date now = new Date();
        if (coupon.getValidEndTime().before(now)) {
            throw new ServiceException("优惠券已过期，无法恢复");
        }
        
        // 更新状态为已发布
        return couponManagementMapper.updateCouponStatus(couponId, String.valueOf(merchantId), 3);
    }

    /**
     * 统计优惠券数据
     */
    @Override
    public CouponStatisticsVO getCouponStatistics() {
        // 从token中获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        String merchantIdStr = String.valueOf(merchantId);
        
        CouponStatisticsVO statistics = new CouponStatisticsVO();
        statistics.setTotalCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, null));
        statistics.setPendingCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, 0));
        statistics.setApprovedCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, 1));
        statistics.setRejectedCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, 2));
        statistics.setPublishedCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, 3));
        statistics.setPausedCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, 4));
        statistics.setExpiredCount(couponManagementMapper.countCouponByMerchant(merchantIdStr, 5));
        
        return statistics;
    }

    /**
     * 转换为VO
     */
    private CouponVO convertToVO(CouponManagement2 coupon) {
        CouponVO vo = new CouponVO();
        BeanUtils.copyProperties(coupon, vo);
        
        // 设置类型名称
        vo.setCouponTypeName(getCouponTypeName(coupon.getCouponType()));
        
        // 设置适用范围名称
        vo.setApplicableScopeName(getApplicableScopeName(coupon.getApplicableScope()));
        
        // 设置状态名称
        vo.setStatusName(getStatusName(coupon.getStatus()));
        
        // 设置审核状态名称
        vo.setApprovalStatusName(getApprovalStatusName(coupon.getApprovalStatus()));
        
        return vo;
    }

    /**
     * 验证优惠券参数
     */
    private void validateCouponParams(CouponCreateDTO dto) {
        // 验证时间
        if (dto.getValidEndTime().before(dto.getValidStartTime())) {
            throw new ServiceException("有效期结束时间不能早于开始时间");
        }
        
        if (dto.getReceiveStartTime() != null && dto.getReceiveEndTime() != null) {
            if (dto.getReceiveEndTime().before(dto.getReceiveStartTime())) {
                throw new ServiceException("领取结束时间不能早于开始时间");
            }
        }
        
        // 验证优惠券类型参数
        if (dto.getCouponType() == 1) { // 满减券
            if (dto.getDiscountAmount() == null || dto.getDiscountAmount().compareTo(BigDecimal.ZERO) <= 0) {
                throw new ServiceException("满减券必须设置优惠金额");
            }
        } else if (dto.getCouponType() == 2) { // 折扣券
            if (dto.getDiscountRate() == null || dto.getDiscountRate().compareTo(BigDecimal.ZERO) <= 0
                || dto.getDiscountRate().compareTo(BigDecimal.ONE) >= 0) {
                throw new ServiceException("折扣券折扣率必须在0-1之间");
            }
        }
        
        // 验证适用范围
        if (dto.getApplicableScope() != 1 && (dto.getScopeIds() == null || dto.getScopeIds().isEmpty())) {
            throw new ServiceException("指定商品或分类时必须选择范围");
        }
    }

    /**
     * 生成优惠券编码
     */
    private String generateCouponCode() {
        return "CPN" + System.currentTimeMillis() + (int)(Math.random() * 9000 + 1000);
    }

    /**
     * 获取优惠券类型名称
     */
    private String getCouponTypeName(Integer type) {
        switch (type) {
            case 1: return "满减券";
            case 2: return "折扣券";
            case 3: return "免费券";
            case 4: return "新用户券";
            default: return "未知";
        }
    }

    /**
     * 获取适用范围名称
     */
    private String getApplicableScopeName(Integer scope) {
        switch (scope) {
            case 1: return "全部商品";
            case 2: return "指定商品";
            case 3: return "指定分类";
            default: return "未知";
        }
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        switch (status) {
            case 0: return "待审核";
            case 1: return "审核通过";
            case 2: return "审核拒绝";
            case 3: return "已发布";
            case 4: return "已暂停";
            case 5: return "已过期";
            default: return "未知";
        }
    }

    /**
     * 获取审核状态名称
     */
    private String getApprovalStatusName(Integer status) {
        switch (status) {
            case 0: return "待审核";
            case 1: return "审核通过";
            case 2: return "审核拒绝";
            default: return "未知";
        }
    }
}

